package luminus.origin

import luminus.origin.utils.Configurations.config
import org.bukkit.event.player.PlayerJoinEvent
import org.bukkit.event.player.PlayerQuitEvent
import taboolib.common.LifeCycle
import taboolib.common.io.newFile
import taboolib.common.platform.Awake
import taboolib.common.platform.event.EventPriority
import taboolib.common.platform.event.SubscribeEvent
import taboolib.common.platform.function.disablePlugin
import taboolib.common.platform.function.getDataFolder
import taboolib.common.platform.function.submit
import taboolib.expansion.PlayerDatabase
import taboolib.expansion.releasePlayerDataContainer
import taboolib.expansion.setupDataContainer
import taboolib.expansion.setupPlayerDatabase


object Database : PlayerDatabase() {
    @Awake(LifeCycle.ENABLE)
    fun init() {
        try {
            if (config.getBoolean("database.enable")) {
                setupPlayerDatabase(config.getConfigurationSection("Database")!!)
            } else {
                setupPlayerDatabase(newFile(getDataFolder(), "data.db"))
            }
        } catch (ex: Throwable) {
            ex.printStackTrace()
            disablePlugin()
            return
        }
    }

    @SubscribeEvent(EventPriority.HIGHEST)
    private fun onJoin(e: PlayerJoinEvent) {
        submit(async = true) {
            e.player.setupDataContainer()
        }
    }

    @SubscribeEvent(EventPriority.HIGHEST)
    private fun onQuit(e: PlayerQuitEvent) {
        e.player.uniqueId.releasePlayerDataContainer()
    }

}